//
//  WCNMeEditVC.m
//  WCN
//
//  Created by 杨鑫 on 15/6/1.
//  Copyright (c) 2015年 ShanghaiCize Trade And Business Co., Ltd. All rights reserved.
//

#import "WCNMeEditVC.h"
#import "WCNSelectHospitalOrWardVC.h"
#import "WCNMulTextEditVC.h"
//
#import "WCNIconLabelTCell.h"
#import "WCNMulTextTCell.h"
//
#import "WCButton.h"
#import "WCInfoEditView.h"
#import "WCDatePickerView.h"
#import "LCActionSheet.h"
//
#import "NSString+Utilities.h"
#import "UINavigationItem+Offset.h"
#import "UILabel+Utilities.h"
#import "NSDate+Utilities.h"
#import "NSObject+Utilities.h"
//
#import "WCDefaultManager.h"
#import "WCImageManager.h"
#import "WCCoreDataStore.h"
#import "WCPopupLayerManager.h"
#import "WCNetworkAccessManager.h"
//
#import "Macros.h"
#import "Constants.h"
#import "WCImageView +setImage.h"
//#import "UserProfileManager.h"

static NSString *avatarId = @"WCNIconLabelTCell";
static NSString *editId = @"WCNMulTextTCell";

@interface WCNMeEditVC () <LCActionSheetDelegate, UINavigationControllerDelegate, UIImagePickerControllerDelegate>

@property (nonatomic, strong) WCNMulTextTCell *prototypeCell;
@property (strong, nonatomic) AccountEntity *account;

@end

@implementation WCNMeEditVC

- (instancetype)init
{
    self = [super initWithStyle:UITableViewStyleGrouped];
    if (self) {
        self.title = @"我的资料";
        self.account = [[WCDefaultManager shareMg] accountEntity];
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    WCButton *rightBtn = [WCButton wcButtonWithType:WCButtonTypeSave];
    [rightBtn addTarget:self action:@selector(save) forControlEvents:UIControlEventTouchUpInside];
    [self.navigationItem addRightBarButtonItem:rightBtn];
    
    self.view.backgroundColor = kAppBg;
    
    self.tableView.showsVerticalScrollIndicator = NO;
    [self.tableView registerNib:[UINib nibWithNibName:avatarId bundle:nil] forCellReuseIdentifier:avatarId];
    [self.tableView registerNib:[UINib nibWithNibName:editId bundle:nil] forCellReuseIdentifier:editId];
    
    self.prototypeCell = [self.tableView dequeueReusableCellWithIdentifier:editId];
    self.prototypeCell.mulText.numberOfLines = 0;
    //加上跨度约束后，动态计算高度才有效
    [self.prototypeCell.contentView addConstraint:[NSLayoutConstraint constraintWithItem:self.prototypeCell.contentView
                                                                               attribute:NSLayoutAttributeWidth
                                                                               relatedBy:NSLayoutRelationEqual
                                                                                  toItem:nil
                                                                               attribute:NSLayoutAttributeNotAnAttribute
                                                                              multiplier:1
                                                                                constant:kScreenWidth]];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    [self.tableView reloadData];
}

#pragma Button Target

- (void)save
{
    if (!self.account.wardId) {
        [[WCPopupLayerManager shareMg] showTextOnly:@"请选择病区" withView:self.view];
        return;
    }
    
    MBProgressHUD *hud = [[WCPopupLayerManager shareMg] showSimple:self.navigationController.view];
    NSMutableDictionary *params = [NSMutableDictionary dictionaryWithDictionary:[self.account dictionaryWithValuesForKeys:@[@"name", @"sex", @"mail", @"birthday", @"intro", @"hospitalId", @"hospitalName", @"wardId", @"wardName"]]];
    [params setValue:self.account.stringId forKey:@"id"];
    
    [[WCNetworkAccessManager sharedMg] POST:@"nurse/account/update" parameters:params success:^(NSDictionary *result){
        [[WCPopupLayerManager shareMg] showTextOnly:result[@"errMsg"] withView:self.view];
        [[WCDefaultManager shareMg] updateAccount:self.account];
        [self performBlock:^{
            [self.navigationController popViewControllerAnimated:YES];
        } afterDelay:.3];
    } failure:nil netError:nil always:^{
        [hud hide:YES];
    }];
}

#pragma mark - <UITableViewDelegate, UITableViewDataSource>

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        return 1;
    } else if(section == 1) {
        return 9;
    } else {
        return 0;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        return 80;
    } else if (indexPath.section == 1) {
        if (indexPath.row == 8) {
            self.prototypeCell.mulText.text = self.account.intro;
            [self.prototypeCell.mulText showAttributedText:0 lineSpace:5];
            
            CGSize size = [self.prototypeCell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize];
            return MAX(kOnePX+size.height, 44.0);
        }
        return 44.0;
    } else {
        return .0;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        WCNIconLabelTCell *cell = [tableView dequeueReusableCellWithIdentifier:avatarId forIndexPath:indexPath];
        
        cell.leftIcon.layer.cornerRadius = 30;
        cell.leftIcon.clipsToBounds = YES;
        
        cell.iconheight.constant = 60;
        cell.iconwidth.constant = 60;
        cell.superLeadingIcon.constant = 14;
        cell.iconLeadingLabel.constant = 20;
        
       
        
        UIImage *image = [[WCImageManager sharedMg] image:self.account.stringId type:WCImageTypeNurse size:WCImageSizeSmall cache:YES];
        if (image) {
            cell.leftIcon.image = image;
        } else {
            cell.leftIcon.image = [UIImage imageNamed:@"Nurse_default"];
            
            MBProgressHUD *hud = [[WCPopupLayerManager shareMg] showSimpleInImageView:cell.leftIcon];
            [[WCImageManager sharedMg] downloadImage:self.account.stringId type:WCImageTypeNurse size:WCImageSizeSmall cache:YES success:^(UIImage *image, NSString *stringId){
                cell.leftIcon.image = image;
                
                [hud hide:YES];
            } failure:^(id error){
                [hud hide:YES];
            }];
        }
//
        cell.iconTitle.text = @"选择头像";
        
        return cell;
    } else if (indexPath.section == 1) {
        WCNMulTextTCell *cell = [tableView dequeueReusableCellWithIdentifier:editId forIndexPath:indexPath];
        
        cell.mulText.numberOfLines = 1;
        switch (indexPath.row) {
            case 0:{
                cell.textTitle.text = @"手机号";
                cell.mulText.text = self.account.mobile;
                break;
            }
            case 1:{
                cell.textTitle.text = @"二维码名片";
                cell.mulText.hidden = YES;
                if (self.account.qrCode) {
                    NSString *url = [[UIImageView getimageUrlForMedia] stringByAppendingString:self.account.qrCode];
                    UIImageView *qrCodeImageView = [[UIImageView alloc] initWithFrame:CGRectMake(kScreenWidth - 60, 7, 30, 30)];
                    qrCodeImageView.tag = 100001;
                    [qrCodeImageView setImageWithURL:[NSURL URLWithString:url]];
                    [cell.contentView addSubview:qrCodeImageView];
                    
                }
                break;
            }
            case 2:{
                cell.mulText.text = self.account.hospitalName;
                cell.textTitle.text = @"医院";
                break;
            }
            case 3:{
                cell.textTitle.text = @"病区";
                cell.mulText.text = self.account.wardName;
                break;
            }
            case 4:{
                cell.textTitle.text = @"姓名";
                cell.mulText.text = self.account.name;
                break;
            }
            case 5:{
                cell.textTitle.text = @"性别";
                cell.mulText.text = self.account.sexStr;
                break;
            }
            case 6:{
                cell.textTitle.text = @"生日";
                cell.mulText.text = self.account.birthday;
                break;
            }
            case 7:{
                cell.textTitle.text = @"邮箱";
                cell.mulText.text = self.account.mail;
                break;
            }
            case 8:{
                cell.textTitle.text = @"自我介绍";
                cell.mulText.numberOfLines = 0;
                cell.mulText.text = self.account.intro;
                [cell.mulText showAttributedText:0 lineSpace:5];
                break;
            }
        }
        
        return cell;
    } else {
        return nil;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if (indexPath.section == 0) {
        LCActionSheet *sheet = [LCActionSheet sheetWithTitle:nil buttonTitles:@[@"拍照", @"相册"] redButtonIndex:-1 delegate:self];
        sheet.tag = 0;
        [sheet showInView:self.navigationController.view];
    } else if (indexPath.section == 1) {
        WCNMulTextTCell *cell = (WCNMulTextTCell *)[tableView cellForRowAtIndexPath:indexPath];
        switch (indexPath.row) {
            case 0: {
                break;
            }
            case 1: {
                UIImageView *imageView = [cell.contentView viewWithTag:100001];
                UIImage *image = imageView.image;
                [imageView zoomImagefromImage:image fromViewController:self];
                break;
            }
                
            case 2: {
                /**
                 此功能暂时屏蔽
                 
                 WCNSelectHospitalOrWardVC *vc = [[WCNSelectHospitalOrWardVC alloc] init];
                 vc.title = @"选择医院";
                 vc.selectMode = WCNSelectVCHospital;
                 vc.account = self.account;
                 [self.navigationController pushViewController:vc animated:YES];

                 */
                                break;
            }
            case 3: {
                
                /**
                 此功能暂时屏蔽
                 WCNSelectHospitalOrWardVC *vc = [[WCNSelectHospitalOrWardVC alloc] init];
                 vc.title = @"选择病区";
                 vc.selectMode = WCNSelectVCWard;
                 vc.account = self.account;
                 [self.navigationController pushViewController:vc animated:YES];
                 
                 */
                break;
            }
            case 4: {
                /**
                 此功能暂时屏蔽
                 
                 WCInfoEditView *editView = [[WCInfoEditView alloc] init];
                 editView.titleLabel.text = @"编辑姓名";
                 editView.textField.text = self.account.name;
                 editView.save = ^(NSString *txt){
                 if (![txt isEmpty]) {
                 self.account.name = txt;
                 cell.mulText.text = txt;
                 return YES;
                 }
                 return NO;
                 };
                 [editView showIn:self.navigationController.view animated:YES];

                 */
                break;
            }
            case 5: {
                /**
                 此功能暂时屏蔽
                 *   LCActionSheet *sheet = [LCActionSheet sheetWithTitle:nil buttonTitles:@[@"男", @"女"] redButtonIndex:-1 delegate:self];
                 sheet.tag = 1;
                 [sheet showInView:self.navigationController.view];

                 */
                break;
            }
            case 6: {
                
                WCDatePickerView *datePicker = [[WCDatePickerView alloc] init];
                datePicker.dateLabel.text = @"选择出生日期";
                if (!self.account.birthday || [self.account.birthday isEmpty]) {
                    datePicker.datePicker.date = [NSDate date];
                } else {
                    datePicker.datePicker.date = [self.account.birthday toDate:nil];
                }
                datePicker.datePicker.maximumDate = [NSDate date];
                datePicker.close = ^(NSDate *date){
                    self.account.birthday = [date stringWithFormat:@"yyyy-MM-dd"];
                    cell.mulText.text = self.account.birthday;
                };
                [datePicker show:self.navigationController completion:nil];
                break;
            }
            case 7: {
                
                WCInfoEditView *editView = [[WCInfoEditView alloc] init];
                editView.titleLabel.text = @"编辑邮箱";
                editView.textField.text = self.account.mail;
                editView.textField.keyboardType = UIKeyboardTypeEmailAddress;
                editView.save = ^(NSString *txt){
                    if ([txt isEmail]) {
                        self.account.mail = txt;
                        cell.mulText.text = txt;
                        return YES;
                    }
                    return NO;
                };
                [editView showIn:self.navigationController.view animated:YES];
                break;
            }
            case 8: {
                WCNMulTextEditVC *vc = [[WCNMulTextEditVC alloc] initWithType:WCNMulTextEditSave];
                vc.title = @"自我介绍";
                vc.textViewPlaceholder = @"请填写自我介绍";
                vc.textViewValue = self.account.intro;
                vc.canEmpty = YES;
                vc.callback = ^(NSString *text){
                    self.account.intro = text;
                    cell.mulText.text = text;
                };
                [self.navigationController pushViewController:vc animated:YES];
                break;
            }
        }
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        return 15;
    }
    
    return 15-kOnePX;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    if (section == 1) {
        return 15;
    }
    
    return kOnePX;
}

#pragma mark - LCActionSheetDelegate

- (void)actionSheet:(LCActionSheet *)actionSheet didClickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (actionSheet.tag == 0) {
        UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
        
        switch (buttonIndex) {
            case 0:{
                if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera ]) {
                    imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
                    break;
                }
            }
            case 1:{
                imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
                break;
            }
                
            default:{
                return;
            }
        }
        
        imagePicker.delegate = self;
        imagePicker.allowsEditing = YES;
        
        [self presentViewController:imagePicker animated:YES completion:nil];
    } else if (actionSheet.tag == 1) {
        if (buttonIndex == 0) {
            self.account.sex = @"MALE";
        } else if (buttonIndex == 1) {
            self.account.sex = @"FEMALE";
        }
        NSIndexPath *reloadRow = [NSIndexPath indexPathForRow:4 inSection:1];
        [self.tableView reloadRowsAtIndexPaths:@[reloadRow] withRowAnimation:UITableViewRowAnimationNone];
    }
}

#pragma mark - UIImagePickerControllerDelegate

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    UIImage *img = info[UIImagePickerControllerEditedImage];
    
    MBProgressHUD *hud = [[WCPopupLayerManager shareMg] showSimple:self.view];
    [[WCImageManager sharedMg] uploadImage:@[img] multi:NO progress:^(NSProgress *progress) {
        
       
        
        
    } success:^(NSDictionary *result){
        [hud hide:YES];
        [self loadUserAvatar:result[@"data"]];
    } failure:^(NSString *msg){
        [hud hide:YES];
        [[WCPopupLayerManager shareMg] showTextOnly:msg withView:self.view];
    }];
    
    [picker dismissViewControllerAnimated:YES completion:nil];
}

- (void)loadUserAvatar:(NSDictionary *)data
{
    MBProgressHUD *hud = [[WCPopupLayerManager shareMg] showSimple:self.view];
    [[WCNetworkAccessManager sharedMg] POST:@"nurse/account/avatar/upload" parameters:@{@"nurseId":self.account.stringId, @"fileId":data[@"name"]} success:^(NSDictionary *result){
        [[WCImageManager sharedMg] downloadImage:self.account.stringId type:WCImageTypeNurse size:WCImageSizeSmall cache:YES success:^(UIImage *image, NSString *stringId){
            
//            [[UserProfileManager sharedInstance] uploadUserHeadImageProfileInBackground:image completion:^(BOOL success, NSError *error) {
//                if (success) {
//                    Log(@"上传图像成功");
//                }
//            }];

            NSIndexPath *reloadRow = [NSIndexPath indexPathForRow:0 inSection:0];
            [self.tableView reloadRowsAtIndexPaths:@[reloadRow] withRowAnimation:UITableViewRowAnimationNone];
        } failure:nil];
    } failure:nil netError:nil always:^{
        [hud hide:YES];
    }];
}

@end
